/* eslint-disable camelcase */
import {
  log
} from '../../share/index'
import {
  verifyCollection
} from '../utils/config'

export class VerifyCode {
  async setVerifyCode ({
    clientIP,
    deviceId,
    code,
    expiresDate,
    scene
  }) {
    if (!deviceId) {
      return {
        code: 10101,
        msg: 'deviceId不可为空'
      }
    }

    if (!code) {
      return {
        code: 10102,
        msg: '验证码不可为空'
      }
    }

    if (!expiresDate) {
      expiresDate = 180 // 默认180s过期时间
    }

    const now = Date.now()
    const record = {
      device_uuid: deviceId,
      scene,
      code: code.toLocaleLowerCase(),
      state: 0,
      // 是否允许跨设备还有待讨论
      ip: clientIP,
      created_date: now,
      expired_date: now + expiresDate * 1000
    }

    const addRes = await verifyCollection.add(record)
    log('addRes', addRes)
    return {
      code: 0,
      deviceId
    }
  }

  async verifyCode ({
    deviceId,
    code,
    scene
  }) {
    if (!deviceId) {
      return {
        code: 10101,
        msg: 'deviceId不可为空'
      }
    }

    if (!code) {
      return {
        code: 10102,
        msg: '验证码不可为空'
      }
    }

    const now = Date.now()
    const query = {
      device_uuid: deviceId,
      scene,
      code: code.toLocaleLowerCase(),
      state: 0
    }

    const record = await verifyCollection.where(query).orderBy('created_date', 'desc').limit(1).get()

    log('verifyRecord:', record)

    if (record && record.data && record.data.length > 0) {
      // 验证通过
      const matched = record.data[0]

      if (matched.expired_date < now) {
        return {
          code: 10103,
          msg: '验证码已失效'
        }
      }

      // 状态改为已验证
      const upRes = await verifyCollection.doc(matched._id).update({
        state: 1
      })
      log('upRes', upRes)
      return {
        code: 0,
        msg: '验证通过'
      }
    } else {
      return {
        code: 10104,
        msg: '验证码错误'
      }
    }
  }
}
